package Twitim::API::DirectMessages;

use strict;
use warnings;

use HTML::Entities;
use base qw( Twitim::API );

sub _start {
    my ( $self, $output ) = @_;

    my %extra;
    if ( $self->{'max_dm_id'}
        && !( $output && $output eq 'Direct Messages' ) )
    {
        $extra{'since_id'} = $self->{'max_dm_id'};
    }

    $self->_getfromapi( 'direct_messages', '.json', $output, \%extra );
}

sub _last {
    my ( $self, $array_ref, $output ) = @_;

    @{$array_ref} = sort { $a->{'id'} <=> $b->{'id'}; } @{$array_ref};

    foreach my $hash_ref (@$array_ref) {
        my $jid    = $hash_ref->{'sender_screen_name'};
        my $id     = $hash_ref->{'id'};
        my $body   = $hash_ref->{'text'};
        my $time   = $self->get_unixtime( $hash_ref->{'created_at'} );
        my $source = $hash_ref->{'source'};

        Twitim::NetBase->set_username( $jid, $hash_ref->{'sender'}{'name'} );
        Twitim::NetBase->set_userid( $jid, $hash_ref->{'sender'}{'id'} );
        Twitim::NetBase->set_icon( $jid,
            $hash_ref->{'sender'}{'profile_image_url'} );
#        $self->{'max_dm_id'} = $id if $self->{'max_dm_id'} < $id;

        $self->{'cb'}->{'message'}->(
            {   user_id    => "Direct from $jid",
                body       => decode_entities($body),
                message_id => "d_$id",
                unixtime   => $time,
                source     => $source,
                output     => $output
            }
        );
    }
    return;
}

1;
